﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetOpenAuth.AspNet.Clients;
using Newtonsoft.Json;
namespace DotNetOpenAuth.AspNet.Clients
{
    public class BaiduClient : OAuth2Client
    {
        public string APIKey { get; private set; }
        public string APISecret { get; private set; }
        public BaiduClient(string Key, string Secret)
            : base("百度")
        {
            APIKey = Key;
            APISecret = Secret;
        }

        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            string str = string.Format("https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id={0}&redirect_uri={1}&state={2}&display=page", APIKey, GetEncodeUrl(returnUrl), "Test");
            return new Uri(str);
        }

        private string GetEncodeUrl(Uri returnUrl)
        {
#if DEBUG
            return "oob";
#else
            return Uri.EscapeDataString(returnUrl.ToString());
#endif
        }

        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            string str = string.Format("https://openapi.baidu.com/rest/2.0/passport/users/getInfo?access_token={0}", accessToken);
            dynamic result = GetData(str);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["id"] = result.userid;
            dic["username"] = result.username;
            return dic;
        }

        protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            string str = string.Format("https://openapi.baidu.com/oauth/2.0/token?client_id={0}&client_secret={1}&grant_type=authorization_code&code={2}&redirect_uri={3}", APIKey, APISecret, authorizationCode, GetEncodeUrl(returnUrl));
            //string str = string.Format("https://openapi.baidu.com/oauth/2.0/token?client_id={0}&client_secret={1}&grant_type=authorization_code&code={2}&redirect_uri={3}", APIKey, APISecret, authorizationCode,"oob");
            dynamic result = GetData(str);
            return result.access_token;
        }

        private dynamic GetData(string str)
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            var t = client.GetStringAsync(str).Result;
            var obj = JsonConvert.DeserializeObject(t);
            return obj;
        }
    }
}